package com.javasearch.utils;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WriteFileStrUtil {


    /**
     * 将字符串写入文本中,(追加方式)
     *
     * @param path 写入的文件
     * @param str  需要追加的字符串
     */
    public static void writeStrAppend(File path, String str) {
        writeStr(path, str, true);
    }




    /**
     * 将字符串写入文本中,(覆盖方式)
     *
     * @param path 写入的文件
     * @param str  需要追加的字符串
     */
    public static void writeStrCover(File path, String str) {
        writeStr(path, str, false);
    }

    private static void writeStr(File path, String str, boolean type) {
        try (BufferedWriter bw =
                     new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path, type)));) {
            bw.write(str);
            bw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static  Map<String,Object>  map=new ConcurrentHashMap<>();
    //将字符串写入文本中,(追加方式),加锁
    public static void writeStrLock(File path, String str,boolean mode) {
        boolean b = map.containsKey(path.getAbsolutePath());
        while (b){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            b = map.containsKey(path.getAbsolutePath());
        }
        map.put(path.getAbsolutePath(),new Object());
        try (
                FileOutputStream fileOutputStream = new FileOutputStream(path, mode);
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
        ) {
            bw.write(str);
            bw.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            map.remove(path.getAbsolutePath());
        }
    }

}
